package com.tree.backend.controller;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.tree.backend.common.Result;
import com.tree.backend.entity.dto.UserDTO;
import com.tree.backend.entity.pojo.User;
import com.tree.backend.entity.vo.UserVO;
import com.tree.backend.service.IUserService;
import com.tree.backend.utils.UserContext;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;


@RestController
@RequiredArgsConstructor
@RequestMapping("/user")
public class UserController {
    private final IUserService userService;

    @GetMapping("/list")
    public Result<Page<UserVO>> getList(UserDTO userDTO) {
        return userService.getList(userDTO);
    }


    @DeleteMapping("/{id}")
    public Result<Boolean> delete(@PathVariable("id") Long id) {
        return Result.success(userService.removeById(id));
    }

    @PutMapping
    public Result<Boolean> update(@RequestBody UserDTO userDTO) {
        // 直接转换
        User user = new User();
        BeanUtils.copyProperties(userDTO, user);
        if (StringUtils.hasText(user.getPassword())) user.setPassword(null);
        return Result.success(userService.updateById(user));
    }

    @PostMapping
    public Result<Boolean> add(@RequestBody UserDTO userDTO) {
        User user = new User();
        BeanUtils.copyProperties(userDTO, user);
        user.setCompanyId(UserContext.getCompanyId());
        return Result.success(userService.save(user));
    }
    
    // 获取当前登录用户信息
    @GetMapping("/current")
    public Result<UserVO> getCurrentUser() {
        return userService.getCurrentUser();
    }
}
